thin.imports('/public/plug/domtoimage/dom-to-image.js');
thin.imports('/public/configure/conf.bp.js');
thin.imports('/public/webfe/resource/lazyImage.js');
thin.imports('/public/plug/LoadEffect/LoadEffect.js');

thin.use(function() {
	// 頁面加載完畢
	thin.effect();

	var lazy = thin.lazyImage;
	lazy();

	//var domtoimage = require('dom-to-image');

	/*$(document).on('keyup', '#plestext', function() {
		var remain = $(this).val().length;
		if(remain > 500) {
			pattern = "字数超过限制！";
		} else {
			var result = limitNum - remain;
			pattern = '还可以输入' + result + '字符';
		}
		$('#contentwordage').html(pattern);
	});*/

	$('.bpmodal').on('click', 'a', function() {
		var that = $(this);
		var length = that.attr('data-length');
		var ele = '<textarea id="plestext" maxlength="' + length + '" ></textarea><p class="m-x-2x c-888">还可以输入' + length + '字数</p>';

		layer.open({
			type: 1,
			title: '请输入',
			content: ele,
			area: ['480px', 'auto'],
			btn: ['确定', '取消'],
			yes: function(index) {
				var val = $('#plestext').val();
				that.html(val);
				layer.close(index);
			},
			btn2: function(index) {
				layer.close(index);
			}
		});
	});

	$('#submit-createbp').on('click', submitCreateBP);

	$('.prev').on('click', function() {
		nowPage--;
		if(nowPage < 1) nowPage = 1;
		window.location.href = '#tpl-step' + nowPage;
	});

	$('.next').on('click', function() {
		nowPage++;
		if(nowPage > 30) nowPage = 30;
		window.location.href = '#tpl-step' + nowPage;
	});

});

var bp_list = [],
	__getdata_bpcreate = {},
	bp_index = 0,
	nowPage = 1;

function dlll(elem_id, cb) {
	//dlll('tpl-step1')
	var node = document.getElementById(elem_id);
	domtoimage.toPng(node).then(cb).catch(function(error) {
		//console.error('oops, something went wrong!', error);
	});
}

// 填写计划书标题
function submitCreateBP() {
	layer.prompt({
		title: '请输入商业计划书标题',
		formType: 0
	}, function(text, index) {
		if(text == '') {

		} else {
			__getdata_bpcreate['title'] = text;
			createImages();
			layer.close(index);
		}
	});
}

// 生成图片
function createImages() {
	layer.load(0, {
		shade: [0.08, '#000']
	});
	bp_list = [];
	/*for (var i = 1; i <= 30; i++) {
		dlll('tpl-step' + i);
	}*/
	// 递归执行
	recursion();
}

// 递归执行
function recursion() {
	bp_index = bp_index + 1;
	dlll('tpl-step' + bp_index, function(dataUrl) {
		var str = dataUrl.replace('data:image/png;base64,', '');
		bp_list.push(str);
		//console.dir(bp_index);
		if(bp_index >= 30) {
			submitBP();
		} else {
			recursion();
		}
	});
}

// 提交数据
function submitBP() {
	__getdata_bpcreate['imgArr'] = JSON.stringify(bp_list);
	factory.request('_bp_create');
}

// 创建商业计划书回调
function __complete_bpcreate(res) {
	layer.closeAll('loading');
	if(res.status == 201) {
		layer.msg('项目创建成功', {
			icon: 1,
			time: 1200
		}, function() {
			//window.location.href = '/member.html#member';
			tool.__cookie.set('pdf_uri', res.data.uri);
			window.location.href = '/pdf.html';
		});
	} else {
		layer.msg(res.error, {
			icon: 2,
			time: 800
		});
	}
}